package com.lazy.book.common.exception;

import cn.dev33.satoken.exception.NotLoginException;
import cn.dev33.satoken.exception.NotPermissionException;
import com.lazy.book.common.enums.CommonResponseEnum;
import com.lazy.book.common.entity.ApiResult;
import org.springframework.core.annotation.Order;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

@Order(Integer.MIN_VALUE)
@RestControllerAdvice
public class SaExceptionHandler {
  @ExceptionHandler(NotLoginException.class)
  public ApiResult<Void> handlerNotLoginException(NotLoginException e) {
    String message = switch (e.getType()) {
      case NotLoginException.NOT_TOKEN -> "未能读取到有效 token";
      case NotLoginException.INVALID_TOKEN, NotLoginException.TOKEN_FREEZE ->
          "您的登录信息已过期，请重新登录以继续访问。";
      case NotLoginException.TOKEN_TIMEOUT -> "token 已过期";
      case NotLoginException.BE_REPLACED -> "token 已被顶下线";
      case NotLoginException.KICK_OUT -> "token 已被踢下线";
      case NotLoginException.NO_PREFIX -> "未按照指定前缀提交 token";
      default -> "当前会话未登录";
    };
    return new ApiResult<>(CommonResponseEnum.INVALID_TOKEN.getCodePrefixEnum().getPrefix() + CommonResponseEnum.INVALID_TOKEN.getCode(), message);
  }

  @ExceptionHandler(NotPermissionException.class)
  public ApiResult<Void> handlerNotPermissionException(NotPermissionException e) {
    return ApiResult.error(CommonResponseEnum.INVALID_PERMISSION);
  }
}
